package com.lizk.study.netty.day003;

import com.lizk.study.netty.entity.ServerContent;
import com.lizk.study.netty.utils.NettyUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author lizhikui
 * @date 2019/6/17 23:17
 */
public class BeartbeatServer {

    public static void main(String[] args) throws InterruptedException {
        ServerContent serverContent = NettyUtils.createServerContent(NioServerSocketChannel.class);
        serverContent.getServerBootstrap().handler(new LoggingHandler(LogLevel.INFO))
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new IdleStateHandler(5,6,7))
                .addLast(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if(evt instanceof IdleStateEvent){
                            switch (((IdleStateEvent) evt).state()) {
                                case READER_IDLE:
                                    System.out.println("读空闲");
                                    break;
                                case WRITER_IDLE:
                                    System.out.println("写空闲");
                                    break;
                                case ALL_IDLE:
                                    System.out.println("全超时");
                                    break;
                            }
                        }
                    }
                });
            }
        });


        try {
            NettyUtils.bind(serverContent,9999);
        }finally {
            NettyUtils.stop(serverContent);
        }


    }


}
